package com.ihd.ihardware.view.scooter.model;

import com.google.gson.JsonObject;
import com.ihd.ihardware.api.HttpClient;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.pojo.DeviceListRes;
import com.ihd.ihardware.pojo.EmptyRes;

import org.reactivestreams.Publisher;

import cn.wowjoy.commonlibrary.http.BaseSubscriber;
import cn.wowjoy.commonlibrary.utils.RxSchedulerTransformer;
import cn.wowjoy.commonlibrary.viewmodel.BaseRepository;
import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SCRepository extends BaseRepository {

    public void bind(String originalData) {
        JsonObject mParam = new JsonObject();
        mParam.addProperty("originalData", originalData);
        mParam.addProperty("type", "4");
        RequestBody rb = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mParam.toString());
        addDisposable(HttpClient.getService().bind(rb)
                .flatMap(new Function<EmptyRes, Publisher<DeviceListRes>>() {
                    @Override
                    public Publisher<DeviceListRes> apply(EmptyRes emptyRes) throws Exception {
                        if (emptyRes.getCode() == 0)
                            return HttpClient.getService().deviceList(1, 100);
                        else {
                            return Flowable.error(new Exception(emptyRes.getMessage()));
                        }
                    }
                })
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<DeviceListRes>(AppConstans.BIND) {
                }));
    }

    public void unbind(String id) {
        addDisposable(HttpClient.getService().unbind(id)
                .flatMap(new Function<EmptyRes, Publisher<DeviceListRes>>() {
                    @Override
                    public Publisher<DeviceListRes> apply(EmptyRes emptyRes) throws Exception {
                        if (emptyRes.getCode() == 0)
                            return HttpClient.getService().deviceList(1, 100);
                        else {
                            return Flowable.error(new Exception(emptyRes.getMessage()));
                        }
                    }
                })
                .compose(new RxSchedulerTransformer<>())
                .subscribeWith(new BaseSubscriber<DeviceListRes>(AppConstans.UNBIND) {
                }));
    }
}
